<?php

namespace App\Http\Model;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class FinanceKk extends Base
{
    protected $table = 'finance_kk_stream';
    private $redis_cache_finance_user_wallet = "CACHE:FINANCE:USER:WALLET";
    private $redis_cache_finance_user_kk_today = "CACHE:FINANCE:USER:KK:TODAY:"; //  CACHE:FINANCE:USER:KK:DAY:20171010

    //金币零钱凑整到账数据缓存 单位厘
    protected $userGiftGetKkLessCache = 'FINANCE:USERGIFTGETKKLESS:';//string FINANCE:USERGIFTGETKKLESS:{user_id} => {num}

    public function __construct(array $attributes = [])
    {
        $this->tablePrefix = env('DB_PREFIX');
        parent::__construct($this->table, $attributes);
    }


    /**
     * 更新用户金币数
     * @param int $user_id 更新该user_id的金币
     * @param int $from_user_id 来源于哪个uer_id
     * @param int $room_id 房间id
     * @param int $kk_type 
     * @param int $kk_value 增加/减少多少金币，支出使用负数
     * @param string $kk_desc 描述
     * @return bool
     */
    public function inc($user_id, $from_user_id, $room_id, $kk_type, $kk_value, $kk_desc){
        if(empty($kk_value)) {
            return true;
        }
        if(empty($user_id)) {
            return false;
        }
        DB::table("finance_wallet")
            ->where('user_id', '=', $user_id)
            ->increment('kk_balance',$kk_value,['change_timestamp'=> time()]);

        $wallet = DB::table('finance_wallet')
            ->where('user_id', '=', $user_id)
            ->first(['kk_balance']);

        DB::table("finance_kk_stream")->insert([
            "user_id" => $user_id,
            "room_id" => $room_id,
            "kk_value" => $kk_value,
            "from_user_id" => $from_user_id,
            "kk_type" => $kk_type,
            "kk_desc" => $kk_desc,
            "kk_balance" => $wallet->kk_balance,
            "change_timestamp" => time()
        ]);
        $this->incUserToday($user_id, $kk_value);
        Redis::DEL($this->redis_cache_finance_user_wallet . ':' . $user_id);
        return true;
    }

    /**
     * 累加金币零钱凑整到账数据缓存 单位厘
     */
    public function incrUserGiftGetKkLess($userId, $num){
        $cacheKey = $this->userGiftGetKkLessCache . $userId;
        $res = Redis::INCRBY($cacheKey, $num);
        Redis::EXPIRE($cacheKey, 365*86400);
        return $res;
    }

    /**
     * 累减金币零钱凑整到账数据缓存 单位厘
     */
    public function decrUserGiftGetKkLess($userId, $num){
        $cacheKey = $this->userGiftGetKkLessCache . $userId;
        $res = Redis::DECRBY($cacheKey, $num);
        Redis::EXPIRE($cacheKey, 365*86400);
        return $res;
    }


    /**
     * 累积用户进入收益
     * @param $userId
     * @param $kkValue
     */
    public function incUserToday($userId, $kkValue){
        $redisDay = $this->redis_cache_finance_user_kk_today . date('Ymd', time());
        Redis::HINCRBY($redisDay, $userId, $kkValue);
        if (Redis::TTL($redisDay) < 0){
            Redis::EXPIRE($redisDay, 25*3600);
        }
    }

    /**
     * 用户用户今天收益
     * @param $userId
     * @return int
     */
    public function getUserToday($userId){
        $redisDay = $this->redis_cache_finance_user_kk_today . date('Ymd', time());
        $ret = Redis::HGET($redisDay, $userId);
        if (empty($ret)){
            return 0;
        }
        return intval($ret);
    }



    //金币明细
    public function streams($userId, $page, $page_size)
    {
        $fields = [ 'kk_type', 'kk_desc', 'kk_value', 'change_timestamp'];
        $document = DB::table($this->table)
            ->where('user_id', $userId)
//            ->where('id', '>', 14236901)
//            ->orWhere(function($query) use($userId) {
//                $query->where('from_user_id', $userId)
//                      ->whereIn('kk_type', [11, 12]);
//            })
            ->orderBy('change_timestamp', 'desc')
            ->offset(($page) * $page_size)
            ->limit($page_size)
            ->get($fields);

        $result = self::objToArray($document);

        return $result;
    }


    /**
     * 获取金币提现规则
     * @return mixed
     */
    public function get_kk_rules(){
        $result = DB::table("finance_kk_withdraw_rule")
            ->get();
        return self::objToArray($result);
    }

    /**
     * 今日收入金币
     */
    public function todayIncome($userId) {
        $todayBeginTime = strtotime(date('Y-m-d 00:00:00'));
        $todayEndTime = strtotime(date('Y-m-d 23:59:59'));
        return DB::table($this->table)->where('user_id', $userId)->whereBetween("change_timestamp", [ $todayBeginTime, $todayEndTime ])->where('kk_value','>',0)->sum('kk_value');
    }

    /**
     * 今日支出金币
     */
    public function todaySpending($userId) {
        $todayBeginTime = strtotime(date('Y-m-d 00:00:00'));
        $todayEndTime = strtotime(date('Y-m-d 23:59:59'));
        return DB::table($this->table)->where('user_id', $userId)->whereBetween("change_timestamp", [ $todayBeginTime, $todayEndTime ])->where('kk_value','<',0)->sum('kk_value');
    }
    //金币明细
    public function exchangestreams($userId, $page, $page_size)
    {
        $fields = [ 'kk_type', 'kk_desc', 'kk_value', 'change_timestamp'];
        $document = DB::table($this->table)
            ->where('user_id', $userId)
            ->where('kk_type', 6)
            ->orderBy('change_timestamp', 'desc')
            ->offset(($page) * $page_size)
            ->limit($page_size)
            ->get($fields);
        $result = self::objToArray($document);

        return $result;
    }
}
